//
// Created by xuyf7 on 2021/9/17.
//

#include "JNICallbackHelp.h"
#include "log.h"

JNICallbackHelp::~JNICallbackHelp() {
    vm = 0;
    jniEnv->DeleteGlobalRef(obj);
    obj = 0;
    jniEnv = 0;
}

void JNICallbackHelp::onPrepared(int thread_mode) {
    LOGE("onPrepared");
    if (thread_mode == THREAD_MAIN){
        jniEnv->CallVoidMethod(obj,jmethodId);
    } else if (thread_mode == THREAD_CHILD){
        JNIEnv *newJEnv;
        vm->AttachCurrentThread(&newJEnv,0);
        newJEnv->CallVoidMethod(obj,jmethodId);
        vm->DetachCurrentThread();
    }
}

JNICallbackHelp::JNICallbackHelp(JavaVM *vm, JNIEnv *jniEnv, jobject obj) {
    this->vm = vm;
    this->jniEnv = jniEnv;
    this->obj = jniEnv->NewGlobalRef(obj);
    jclass clazz = jniEnv->GetObjectClass(obj);
    this->jmethodId = jniEnv->GetMethodID(clazz,"onPrepare","()V");
}
